//
//  DBNetworkLogDetailController.m
//  AFNetworking
//
//  Created by HaiOu on 2019/11/8.
//

#import "DBNetworkLogDetailController.h"
#import <QMUIKit/QMUIKit.h>
#import <WebKit/WebKit.h>
#import "Masonry.h"

API_AVAILABLE(ios(8.0))
@interface DBNetworkLogDetailController ()
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView * progressView;
@end

@implementation DBNetworkLogDetailController {
    NSMutableDictionary *valuesInfo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configInit];
    [self configUI];
    [self addObserver];
}

- (void)setModel:(DBNetworkLogModel *)model {
    _model = model;
    valuesInfo = [NSMutableDictionary dictionary];
    if (model.method) {
        [valuesInfo setObject:model.method forKey:@"Method"];
    }
    if (model.uriString) {
        [valuesInfo setObject:model.uriString forKey:@"Url"];
    }
    if (model.parameters) {
        [valuesInfo setObject:model.parameters forKey:@"Parameters"];
    }
    if (model.header) {
        [valuesInfo setObject:model.header forKey:@"Header"];
    }
    if (model.responseObject) {
        [valuesInfo setObject:model.responseObject forKey:@"ResponseObject"];
    }
    if (model.errorDescription) {
        [valuesInfo setObject:[NSNumber numberWithInteger:model.code] forKey:@"Code"];
        [valuesInfo setObject:model.errorDescription forKey:@"Error"];
    }
    [self.webView loadHTMLString:[NSString stringWithFormat:@"<pre>%@</pre>", valuesInfo] baseURL:nil];
}

- (void)configInit {
    
}

- (void)configUI {
    UIBarButtonItem *copy = [[UIBarButtonItem alloc] initWithTitle:@"Copy" style:UIBarButtonItemStylePlain target:self action:@selector(copyDatas)];
    [copy setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = copy;
    
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)copyDatas {
    [[UIPasteboard generalPasteboard] setString:valuesInfo.description];
    QMUITips *tips = [QMUITips createTipsToView:self.navigationController.view];
    QMUIToastAnimator *animator = [[QMUIToastAnimator alloc] initWithToastView:tips];
    animator.animationType = QMUIToastAnimationTypeSlide;
    tips.toastAnimator = animator;
    [tips showSucceed:@"Copied" hideAfterDelay:1];
}

#pragma mark 添加KVO观察者
- (void)addObserver
{
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
}
#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (object == self.webView)
        {
            [self.progressView setAlpha:1.0f];
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f)
            {
                [UIView animateWithDuration:1.5f
                                      delay:0.0f
                                    options:UIViewAnimationOptionCurveEaseOut
                                 animations:^{
                                     [self.progressView setAlpha:0.0f];
                                 }completion:^(BOOL finished) {
                                     [self.progressView setProgress:0.0f animated:NO];
                                 }];
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

#pragma mark - 懒加载
#pragma mark WKWebView-Init
- (WKWebView *)webView
API_AVAILABLE(ios(8.0)){
    if (_webView == nil)
    {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 30.f;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        _webView=[[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.backgroundColor = UIColor.whiteColor;
        _webView.allowsBackForwardNavigationGestures = YES;
        [self.view addSubview:_webView];
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _webView;
}

#pragma mark 进度条-Init

- (UIProgressView *)progressView
{
    if (_progressView == nil)
    {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 4)];
        _progressView.tintColor = [UIColor colorWithRed:255/255.0 green:223/255.0 blue:225/255.0 alpha:1.0];
        _progressView.trackTintColor = [UIColor lightGrayColor];
        [self.view addSubview:_progressView];
    }
    return _progressView;
}

- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
